package com.cn.kehong.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class RemoveTextFromImage {
    public static void main(String[] args) throws IOException {
        // 加载图片
        BufferedImage image = ImageIO.read(new File("D:\\1.png"));

        // 转换图片到灰度
        BufferedImage grayImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
        Graphics2D g2d = grayImage.createGraphics();
        g2d.drawImage(image, 0, 0, null);
        g2d.dispose();

        // 应用阈值化处理
        for (int x = 0; x < image.getWidth(); x++) {
            for (int y = 0; y < image.getHeight(); y++) {
                int pixel = grayImage.getRGB(x, y);
                int alpha = 0xff;
                int gray = (pixel >> 16) & 0xff;

                if (gray < 128) {
                    alpha = 0; // 设置文字部分为透明
                }

                pixel = (pixel & 0x00ffffff) | (alpha << 24);
                grayImage.setRGB(x, y, pixel);
            }
        }

        // 保存修改后的图片
        ImageIO.write(grayImage, "JPG", new File("D:\\2.png"));
    }
}